/**
 * @description 资源目录-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const Service = require('./service.js')
const server = require('@daelui/oxkit/dist/server')
const { mimeTypes } = server

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 资源获取
  */
  pool (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let params = action.req.params || {}
      // 查询所有的文件数据
      let list = await this.$service.queryAll({
        params: {
          status: '1',
          id: params.id,
          name: params.id
        },
        excute: {
          operators: [
            {field: 'id', operator: 'EQUAL', calculator: 'OR'},
            {field: 'name', operator: 'EQUAL', calculator: 'OR'}
          ],
          sort: [
            {field: 'createTime', by: 'desc'},
            {field: 'order', by: 'desc'}
          ]
        }
      })
      list = list.data
      list = Array.isArray(list) ? list : []
      let node = list[0] || {}
      // 文件头
      let mime = mimeTypes['.' + node.type] || 'text/plain'
      let resHeaders = { 'Content-Type': mime }
      return {
        type: 'PLAINTEXT',
        data: node.compile || node.data || '',
        resHeaders,
        success: 1
      }
    })
  }
}

module.exports = Controller